package com.example.demo.config;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONUtil;
import com.example.demo.base.LoginUser;
import com.example.demo.base.LoginUserHolder;
import com.example.demo.base.MyRequestWrapper;
import com.example.demo.consts.CommonConstant;
import com.example.demo.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author mldong
 * @date 2023/9/20
 */
public class MySysFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MyRequestWrapper requestWrapper = new MyRequestWrapper((HttpServletRequest) servletRequest);
        String body = requestWrapper.getBody();
        System.out.println(body);
        if(JSONUtil.isTypeJSONObject(body)) {
            QueryParamHolder.set(JSONUtil.toBean(body, Dict.class));
        } else {
            QueryParamHolder.set(Dict.create());
        }
        if(StpUtil.isLogin()) {
            System.out.println(JSONUtil.toJsonStr(StpUtil.getTokenInfo()));
            LoginUser loginUser = BeanUtil.toBean(StpUtil.getExtra(CommonConstant.LOGIN_USER_KEY), LoginUser.class);
            LoginUserHolder.set(loginUser);
        }
        filterChain.doFilter(requestWrapper, servletResponse);
        LoginUserHolder.remove();
    }
}
